#include "RingMigration.hh"

void RingMigration::buildNet() {
    inLength = 1;
    outLength = 1;

    inPids = new int [inLength];
    outPids = new int [outLength];

    int pid = stream->my_pid();
    int total = stream->pnumber();

    outPids[0] = (pid + 1) % total;
    //    if (outPids[0] == 0) outPids[0]++;

    inPids[0] = pid - 1;

    if (inPids[0] == -1) inPids[0] = total - 1;

    //cout << "[pid " << pid << "]" << "outpids " << outPids[0] << ", inpids " << inPids[0] << endl;
}

void RingMigration::inmigrationPolicy(Population *population, ArrayList<Solution>* inmigrants) {

    ArrayList<Solution> *all = population->getAll();

    for (int i = 0; i < inmigrants->length(); i++) {
        Solution *inmigrant = inmigrants->get(i);
        //cout << "[" << stream->my_pid() << "] new solution ";
        //inmigrant->send(cout);
        //cout << endl;

        int dominates = -1;

        for (int j = 0; (j < all->length()) && (dominates == -1); j++) {
            Solution *solution = all->get(j);

            if (inmigrant->dominates(solution)) dominates = j;
        }

        if (dominates != -1) {
            all->remove(dominates);
            all->add(inmigrant, dominates);
            inmigrants->release(i);
            i--;

            //cout << "[" << stream->my_pid() << "] new solution accepted " << endl;

        } //else cout << "[" << stream->my_pid() << "] new solution rejected " << endl;
    }
}
